﻿using ICCardHelper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using PSamResult = ICCardHelper.PSamResult;

namespace ControllerClient
{
    class CommondHelper
    {


        static string PSAMReaderName = ConfigHelper.GetAppConfig("PSAMReaderName");
        static PCSCReader psam = new PCSCReader(PSAMReaderName);

        //static TXTHelper ltSstackCode = new TXTHelper("SstackCode");
       
        static TXTHelper ltsession = new TXTHelper("session");
        static TXTHelper ltskey = new TXTHelper("skey");
        static TXTHelper ltmkey = new TXTHelper("mkey");
      
        static TXTHelper ltid = new TXTHelper("id");
        static TXTHelper ltdata = new TXTHelper("data");
        static TXTHelper lttype = new TXTHelper("decryptType");
        static TXTHelper dataMaker = null;
        //心跳
        public static byte[] HeartConnect(string transport, string way, string logicType)
        {

            byte[] data = new byte[0];
            //data[0] = 0x00;
            //data[1] = 0x00;
            //data[2] = 0x00;
            //data[3] = 0x00;
            byte[] dataAll = HeadUtil(data, 0, transport, "", way);

            //LogHelper.Debug("发送拼接数据总长度" + dataAll.Length);
            LogicHead lh = HeadHelper.analysisData(dataAll);

            return dataAll;
        }
        //1001逻辑硬件初始化--手持机
        public static byte[] HardwareInitialize(string controlId, bool safeTy, string heartTime, string iconPattern,string prefix, string version,bool heartStatu,string transport,string way,string logicType)
        {

            
            LogHelper.Debug("设备id" + controlId);
            //逻辑硬件初始化
            List<byte[]> list = new List<byte[]>();
            StringBuilder sb = new StringBuilder();
            //表示id由用户授予
            string bin = "";
           
            byte[] tokenByte = new byte[4];
           
            if (logicType.Equals("2"))
            {
                if (safeTy)
                {
                    bin =  "10000000000000000000000001001001";
                }
                else
                {
                    bin =  "10000000000000000000000000001001";
                }
                string token = string.Format("{0:x}", Convert.ToInt32(bin, 2));
               
                tokenByte = HexUtils.strToHexByte(token);
                
            }
            //else if (logicType.Equals("3"))
            //{               
            //    id = "1003";
            //    tokenByte[0] = 0x00;
            //    tokenByte[1] = 0x00;
            //    tokenByte[2] = 0x00;
            //    tokenByte[3] = 0x00;
            //}
            //else if (logicType.Equals("4"))
            //{
            //    id = "1004";
            //    tokenByte[0] = 0x00;
            //    tokenByte[1] = 0x00;
            //    tokenByte[2] = 0x00;
            //    tokenByte[3] = 0x00;
            //}
            else if (logicType.Equals("5"))
            {
              
                bin = "10000000000000000000000000101010";
                string token = string.Format("{0:x}", Convert.ToInt32(bin, 2));
                tokenByte = HexUtils.strToHexByte(token);
            }



                list.Add(tokenByte);
           
            int idLen = controlId.Length;
            byte[] idLenByte = HexUtils.intToBytes(idLen);
           // byte[] idByte = HexUtils.strToHexByte(controlId);
            byte[] idByte = Encoding.UTF8.GetBytes(controlId);
            list.Add(idLenByte);
            list.Add(idByte);
            if (prefix == "")
            {
                byte[] prefixLenByte = HexUtils.intToBytes(0);
                list.Add(prefixLenByte);


            }
            else 
            {
                byte[] prefixLenByte = HexUtils.intToBytes(prefix.Length);

                byte[] prefixByte = Encoding.UTF8.GetBytes(prefix);
                list.Add(prefixLenByte);

                list.Add(prefixByte);
            }

            

            string provider = iconPattern;
            byte[] providerLenByte = HexUtils.intToBytes(provider.Length);
            byte[] providerByte = Encoding.UTF8.GetBytes(provider);
            list.Add(providerLenByte);
            list.Add(providerByte);

            
            byte[] versionLenByte = HexUtils.intToBytes(version.Length);
            byte[] versionByte = Encoding.UTF8.GetBytes(version);
            LogHelper.Debug("version" + version);
            list.Add(versionLenByte);
            list.Add(versionByte);
            
            string label = iconPattern;
            byte[] labelLenByte = HexUtils.intToBytes(label.Length);
            byte[] labelByte = Encoding.UTF8.GetBytes(label);
            list.Add(labelLenByte);
            list.Add(labelByte);

            string model = iconPattern;
            byte[] modelLenByte = HexUtils.intToBytes(model.Length);
            byte[] modelByte = Encoding.UTF8.GetBytes(model);
            list.Add(modelLenByte);
            list.Add(modelByte);
            //默认0表示不提供心跳
            byte[] heartBeat = new byte[2];
            if (heartStatu)
            {
                string time = Convert.ToString(int.Parse(heartTime), 16);
                Console.WriteLine("===心跳time" + time);
                //heartBeat = HexUtils.strToHexByte(time);
                heartBeat[0] = 0x27;
                heartBeat[1] = 0x10;
            }
            else
            {
                heartBeat[0]=0x00;
                heartBeat[1] = 0x00;
            }
           
           
            list.Add(heartBeat);
            //1代表手持，2代表门架，3代表ic卡识别器,4代表栅栏门,5代表盘库车
                   
            foreach (byte[] item in list)
            {
                sb.Append(HexUtils.byteToHexStr(item));
            }

            //int payLoadsLen = HexUtils.strToHexByte(sb.ToString()).Length;
                                 
            byte[] dataAll = HeadUtil(HexUtils.strToHexByte(sb.ToString()), 0, transport,"", way);
            
            return dataAll;
        }

        //用于只需返回error
        public static byte[] MachineControlCommond(string error, string json, string transport, string sequence, string way)
        {

            byte[] errorByte = null;
            byte[] errorLen = null;
            int errorByteLen = 0;
            if (error == "" || error == null)
            {
                errorLen = HexUtils.intToBytes(errorByteLen);
            }
            else
            {
                errorByte = Encoding.UTF8.GetBytes(error);
                errorByteLen = errorByte.Length;
                errorLen = HexUtils.intToBytes(errorByteLen);
            }
            byte[] jsonByte = Encoding.UTF8.GetBytes(json);
            byte[] jsonByteLen = HexUtils.intToBytes(jsonByte.Length);
            byte[] data = new byte[8 + errorByteLen + jsonByte.Length];


            Array.Copy(errorLen, 0, data, 0, 4);



            Array.Copy(jsonByteLen, 0, data, 4 + errorByteLen, 4);
            Array.Copy(jsonByte, 0, data, 8 + errorByteLen, jsonByte.Length);
            byte[] dataAll = HeadUtil(data, 1, transport, sequence, way);

            return dataAll;
        }


        //电源管理0x80001
        public static byte[] PowerManager(string error, string sequence,string transport,string way)
        {
            byte[] errorByte = null;
            byte[] errorLen = null;
            byte[] data = null;
            int errorByteLen = 0;
           
            if (error == "" || error == null)
            {
                errorLen = HexUtils.intToBytes(errorByteLen);
                //上电

                bool flag = psam.upPower();
                LogHelper.Debug("上电状态" + flag);
                bool hotFlag = psam.hotReset();
                LogHelper.Debug("热重置状态" + hotFlag);
                //getATR

                string ATR = psam.getAtr();
                Console.WriteLine("ATR==" + ATR);
                byte[] ATRByte = HexUtils.strToHexByte(ATR);
                byte[] ATRlenByte = HexUtils.intToBytes(ATRByte.Length).Skip(3).Take(1).ToArray();
                data = new byte[5 + errorByteLen + ATRByte.Length];
                Array.Copy(errorLen, 0, data, 0, 4);
                Array.Copy(ATRlenByte, 0, data, 4, 1);
                Array.Copy(ATRByte, 0, data, 5, ATRByte.Length);
            }
            else
            {
                errorByte = Encoding.UTF8.GetBytes(error);
                errorByteLen = errorByte.Length;
                errorLen = HexUtils.intToBytes(errorByteLen);
                data = new byte[5 + errorByteLen ];
                Array.Copy(errorLen, 0, data, 0, 4);
                Array.Copy(errorByte, 0, data, 4, errorByteLen);

            }

            
            byte[] dataAll = HeadUtil(data, 1, transport, sequence,way);

           
            //LogHelper.Debug("发送8001==" + HexUtils.byteToHexStr(dataAll));


            return dataAll; 
        }
        //下电
        public static byte[] PowerOff(string error,string sequence, string transport,string way)
        {
            byte[] errorByte = null;
            byte[] errorLen = null;
            byte[] data = null;
            int errorByteLen = 0;

            if (error == "" || error == null)
            {
                errorLen = HexUtils.intToBytes(errorByteLen);
                //下电
                bool flag = psam.DownPower();
                LogHelper.Debug("下电状态" + flag);
                //getATR


                data = new byte[5 + errorByteLen];
                byte[] ATRLenByte = new byte[1] { 0x00 };
                Array.Copy(errorLen, 0, data, 0, 4);
                Array.Copy(ATRLenByte, 0, data, 4, 1);
            }
            else
            {
                errorByte = Encoding.UTF8.GetBytes(error);
                errorByteLen = errorByte.Length;
                errorLen = HexUtils.intToBytes(errorByteLen);
                data = new byte[5 + errorByteLen];
                byte[] ATRLenByte = new byte[1] { 0x00 };
                Array.Copy(errorLen, 0, data, 0, 4);
                Array.Copy(errorByte, 0, data, 4, errorByteLen);
                Array.Copy(ATRLenByte, 0, data, 4+ errorByteLen, 1);


            }




            byte[] dataAll = HeadUtil(data, 1, transport, sequence, way);
            
            return dataAll;
        }
        private static string SendApdu(string apdu)
        {
            LogHelper.Debug("SEND_APDU:" + apdu);
            string returnApdu = "";
            try
            {
                if (apdu.Equals("00A4040009A0000000038698070100")) 
                {
                    apdu = "00A4040009A00000000386980701";
                }
                returnApdu = psam.sendAPDU(apdu);

                LogHelper.Debug("RECV_APDU:" + returnApdu);
                while (returnApdu.Equals("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))
                {
                    LogHelper.Debug("psam卡返回指令不对");
                    psam.DownPower();
                    Thread.Sleep(500);
                    psam.upPower();
                    Thread.Sleep(500);
                    returnApdu = psam.sendAPDU(apdu);

                }
                
            }
            catch (Exception e)
            {
                LogHelper.Debug("读取pasm卡失败" + e);
            }
            return returnApdu;
        }

        //8002数据交换
        public static byte[] dataExchange(string error,string dataControl,string sequence,string mess,string transport,string way)
        {

           
            string apdu = mess.Substring(0 , mess.Length - 8);
            string rh = mess.Substring(mess.Length - 8,4);
            string ch = mess.Substring(mess.Length - 4, 4);
            
            byte[] msg = null;
            byte[] sw = null;
            byte[] msgLen = null;
            string swStr = "";
            string returnApdu = "";
            if (ch.Equals("0000"))
            {
                returnApdu = SendApdu(apdu);
                //Console.WriteLine("apdu==" + returnApdu);
                if (returnApdu.Contains("ERROR"))
                {
                    error = returnApdu;
                }
                else 
                {
                   
                    msg = HexUtils.strToHexByte(returnApdu.Substring(0, returnApdu.Length - 4));

                    sw = HexUtils.strToHexByte(returnApdu.Substring(returnApdu.Length - 4, 4));
                    msgLen = HexUtils.intToBytes(msg.Length + sw.Length);
                    swStr = HexUtils.byteToHexStr(sw);
                }
                
                LogHelper.Debug("CHandler0000" + swStr);
            }
            // 对capdu进行会话处理
            else if (ch.Equals("0001"))
            {
                string vauleOne = apdu.Substring(0, 10);

                string id = apdu.Substring(10, 8);
                string fragment = apdu.Substring(18, 8);
                string flags = apdu.Substring(26, 2);
                if (dataControl == "") 
                {
                    dataControl = ltdata.ReadMessage();

                }
                LogHelper.Debug("0001接收apdu" + apdu);
                dataMaker = new TXTHelper(id + "data");
                dataControl = dataMaker.ReadMessage();
                //id = dataControl.Split(':')[0];
                Console.WriteLine("dataControl====" + dataControl);
                if (dataControl.Length > 0)
                {
                    string datatime = dataControl.Split(':')[1];
                    string dataTo = dataControl.Split(':')[2];
                    string operatorUser = dataControl.Split(':')[3];
                    string auditorUser = dataControl.Split(':')[4];

                    string str = id + fragment + datatime + dataTo + HexUtils.byteToHexStr(HexUtils.intToBytes(int.Parse(operatorUser))) + HexUtils.byteToHexStr(HexUtils.intToBytes(int.Parse(auditorUser)));
                    //LogHelper.Debug("处理前源数据" + str);
                    byte[] shaStrByte = Sha1Hlper.Sha(HexUtils.strToHexByte(str));
                    //LogHelper.Debug("处理后源数据" + HexUtils.byteToHexStr(shaStrByte));


                    apdu = apdu.Substring(0, 34) + HexUtils.byteToHexStr(shaStrByte);// + apdu.Substring(apdu.Length-2,2);
                    //LogHelper.Debug("会话处理后apdu" + apdu);


                    returnApdu = SendApdu(apdu);
                    msg = HexUtils.strToHexByte(returnApdu.Substring(0, returnApdu.Length - 4));

                    sw = HexUtils.strToHexByte(returnApdu.Substring(returnApdu.Length - 4, 4));
                    msgLen = HexUtils.intToBytes(msg.Length + sw.Length);
                    swStr = HexUtils.byteToHexStr(sw);
                }
                else 
                {
                    error = "数据交换出错，找不到任务id";
                }
                

            }
            //LogHelper.Debug("msg" + HexUtils.byteToHexStr(msg));
            //LogHelper.Debug("sw" + HexUtils.byteToHexStr(sw));
            if (swStr.Length > 0) 
            {
                if (swStr.Substring(0, 2).Equals("61"))
                {
                    apdu = "00C00000" + swStr.Substring(2);
                    //LogHelper.Debug("处理前apdu" + apdu);
                    returnApdu = SendApdu(apdu);
                    msg = HexUtils.strToHexByte(returnApdu.Substring(0, returnApdu.Length - 4));

                    sw = HexUtils.strToHexByte(returnApdu.Substring(returnApdu.Length - 4, 4));
                    msgLen = HexUtils.intToBytes(msg.Length + sw.Length);
                }
                else if (swStr.Substring(0, 2).Equals("6C"))
                {
                    string str = swStr.Substring(2, 2);
                    apdu = apdu.Substring(0, apdu.Length - 2) + str;
                    // LogHelper.Debug("修改后处理前apdu" + apdu);
                    returnApdu = SendApdu(apdu);
                    msg = HexUtils.strToHexByte(returnApdu.Substring(0, returnApdu.Length - 4));

                    sw = HexUtils.strToHexByte(returnApdu.Substring(returnApdu.Length - 4, 4));
                    msgLen = HexUtils.intToBytes(msg.Length + sw.Length);
                }
                //LogHelper.Debug("msg" + HexUtils.byteToHexStr(msg));
                //LogHelper.Debug("sw" + HexUtils.byteToHexStr(sw));
                swStr = HexUtils.byteToHexStr(sw);
                if (rh.Equals("8001") && swStr.Equals("9000"))
                {

                    string type = HexUtils.byteToHexStr(msg).Substring(0, 2);
                    LogHelper.Debug("type" + type);
                    lttype.WriteMessage(type);
                    string apduReturn = type;
                    if (swStr.Equals("9000") && type.Equals("02"))
                    {
                        string session = HexUtils.byteToHexStr(msg.Skip(1).Take(1).ToArray());
                        string skey = HexUtils.byteToHexStr(msg.Skip(2).Take(16).ToArray());
                        string mkey = HexUtils.byteToHexStr(msg.Skip(18).Take(16).ToArray());
                        apduReturn = apduReturn + session + "00000000000000000000000000000000" + "00000000000000000000000000000000";
                        msg = HexUtils.strToHexByte(apduReturn);
                        //LogHelper.Debug("存储skey" + skey);
                        //LogHelper.Debug("存储mkey" + mkey);
                        //LogHelper.Debug("存储session" + session);

                        ltskey.WriteMessage(skey);
                        ltmkey.WriteMessage(mkey);
                        ltsession.WriteMessage(session);
                    }
                    else if (swStr.Equals("9000") && type.Equals("01"))
                    {
                        string session = HexUtils.byteToHexStr(msg.Skip(1).Take(1).ToArray());
                        string skey = HexUtils.byteToHexStr(msg.Skip(2).Take(16).ToArray());
                        apduReturn = apduReturn + session + "0000000000000000";
                        msg = HexUtils.strToHexByte(apduReturn);
                        ltskey.WriteMessage(skey);
                        ltsession.WriteMessage(session);
                    }
                    else
                    {
                        returnApdu = SendApdu(apdu);
                        msg = HexUtils.strToHexByte(returnApdu.Substring(0, returnApdu.Length - 4));

                        sw = HexUtils.strToHexByte(returnApdu.Substring(returnApdu.Length - 4, 4));
                        msgLen = HexUtils.intToBytes(msg.Length + sw.Length);
                        swStr = HexUtils.byteToHexStr(sw);
                    }
                    //LogHelper.Debug("msg" + HexUtils.byteToHexStr(msg));
                    //LogHelper.Debug("sw" + HexUtils.byteToHexStr(sw));
                    //LogHelper.Debug("修公正后的apduReturn" + apduReturn);
                }
            }
            
            byte[] errorByte = null;
            byte[] errorLen = null;
            byte[] data = null;
            int errorByteLen = 0;
            if (error == "" || error == null)
            {
                errorLen = HexUtils.intToBytes(errorByteLen);
                data = new byte[4 + errorByteLen + 4 + msg.Length + sw.Length];
            }
            else
            {
                errorByte = Encoding.UTF8.GetBytes(error);
                errorByteLen = errorByte.Length;
                errorLen = HexUtils.intToBytes(errorByteLen);
                data = new byte[4 + errorByteLen + 4];
            }
    
            Array.Copy(errorLen, 0, data, 0, 4);
            if (errorByteLen > 0)
            {
                Array.Copy(errorByte, 0, data, 4, errorByteLen);
                //Array.Copy(msgLen, 0, data, 4 + errorByteLen, 4);
                //Array.Copy(msg, 0, data, 8 + errorByteLen, msg.Length);
                //Array.Copy(sw, 0, data, 8 + errorByteLen + msg.Length, sw.Length);
            }
            else
            {

                Array.Copy(msgLen, 0, data, 4, 4);
                Array.Copy(msg, 0, data, 8, msg.Length);
                Array.Copy(sw, 0, data, 8+ msg.Length, sw.Length);
            }
         
            //LogHelper.Debug("payloads长度" + data.Length);
            byte[] dataAll = HeadUtil(data, 1, transport, sequence,way);           
            return dataAll;

        }
        
        
       
      

        //2001命令
        public static byte[] CommondResponse(string error,string sequence,string transport,string way,string returnJson)
        {
            byte[] errorByte = null;
            byte[] errorLen = null;
            byte[] returnJsonByte = null;
            int errorByteLen = 0;
            int returnJsonLen = 0;
            if (error == "" || error == null)
            {
                errorLen = HexUtils.intToBytes(errorByteLen);
            }
            else
            {
                errorByte = Encoding.UTF8.GetBytes(error);
                errorByteLen = errorByte.Length;
                errorLen = HexUtils.intToBytes(errorByteLen);
            }
            if (returnJson != null)
            {
                returnJsonByte = Encoding.Default.GetBytes(returnJson);
                returnJsonLen = returnJsonByte.Length;
            }
            byte[] dataReturnByte = HexUtils.intToBytes(returnJsonLen);
            byte[] data = new byte[8 + errorByteLen + returnJsonLen];
            if (errorByteLen > 0)
            {
                Array.Copy(errorByte, 0, data, 4, errorByteLen);

            }

            Array.Copy(errorLen, 0, data, 0, 4);
            Array.Copy(dataReturnByte, 0, data, 4 + errorByteLen, 4);
            Array.Copy(returnJsonByte, 0, data, 8 + errorByteLen, returnJsonLen);

            byte[] dataAll = HeadUtil(data, 1, transport, sequence,way);           
            return dataAll;
        }
       
        //4001事件
        public static byte[] EventSelect(string sequence, string transport,string way,string json,string eid)
        {
            //json = File.ReadAllText("事件.txt");
            LogHelper.Debug("json" + json);
            byte[] jsonByte = Encoding.Default.GetBytes(json);
            byte[] jsonLen = HexUtils.intToBytes(jsonByte.Length);
            //byte[] signature = new byte[2] { 0x00, 0x00 };
            //byte[] context = new byte[2] { 0x00, 0x00 };
           
           
            byte[] eidByte = HexUtils.strToHexByte(eid);
           
            //2字节eid+4字节event长度
            byte[] data = new byte[6 + jsonByte.Length];
            
            Array.Copy(eidByte, 0, data, 0, 2);
            //Array.Copy(context, 0, data, 2, 2);
            Array.Copy(jsonLen, 0, data, 2, 4);
            Array.Copy(jsonByte, 0, data, 6, jsonByte.Length);
            //Array.Copy(signature, 0, data, 8 + jsonByte.Length, 2);
           
            
            byte[] dataAll = HeadUtil(data, 1, transport, sequence,way);
            
            //LogHelper.Debug("payloads长度" + data.Length);
            return dataAll;

        }
        public static byte[] EventIC(string sequence, string transport, string way,string atr)
        {
           
            ICEvent ic = new ICEvent();
            ICEventNoATR icNo = new ICEventNoATR();
            string json = "";
            ic.code = "2147745795";
            icNo.code = "2147745795";
            if (atr != "")
            {
                ic.ATR = atr;
                json = JsonConvert.SerializeObject(ic);
            }
            else
            {
                json = JsonConvert.SerializeObject(icNo);
            }
           
            
            
            LogHelper.Debug("json" + json);
            byte[] jsonByte = Encoding.Default.GetBytes(json);
            byte[] jsonLen = HexUtils.intToBytes(jsonByte.Length);
            byte[] signature = new byte[2] { 0x00, 0x00 };
            byte[] context = new byte[2] { 0x00, 0x00 };
            //人员身份采集器
            string eid = "0004";
            
            byte[] eidByte = HexUtils.strToHexByte(eid);
            byte[] data = new byte[10 + +jsonByte.Length];

            Array.Copy(eidByte, 0, data, 0, 2);
            Array.Copy(context, 0, data, 2, 2);
            Array.Copy(jsonLen, 0, data, 4, 4);
            Array.Copy(jsonByte, 0, data, 8, jsonByte.Length);
            Array.Copy(signature, 0, data, 8 + jsonByte.Length, 2);
            LogHelper.Debug("jsonByte" + Encoding.UTF8.GetString(jsonByte));
            byte[] dataAll = HeadUtil(data, 1, transport, sequence, way);
            return dataAll;

        }
        //4003
        public static byte[] UserEmpower(string stackCode, string transport, string way, string userGate, int userGateCount, string sequence)
        {

            
            string aid = stackCode;
            byte[] aidLenByte = HexUtils.intToBytes(aid.Length);


            byte[] aidByte = Encoding.UTF8.GetBytes(aid);
            byte[] countByte = new byte[2];
            
            byte[] commond = new byte[6 + aid.Length+ userGateCount*4];
            switch (userGateCount)
            {
                case 3:
                    countByte[0] = 0x00;
                    countByte[1] = 0x03;
                    break;
                case 2:
                    countByte[0] = 0x00;
                    countByte[1] = 0x02;
                    break;
                case 1:
                    countByte[0] = 0x00;
                    countByte[1] = 0x01;
                    break;
            }
            Array.Copy(aidLenByte, 0, commond, 0, 4);
            Array.Copy(aidByte, 0, commond, 4, aid.Length);
            Array.Copy(countByte, 0, commond, 4 + aid.Length, 2);
            string[] userArr = userGate.Split(',');
            int k = 0;
            foreach (string item in userArr)
            {

                
                if (item != null && item != "")
                {
                    int circleLen = k * 4;
                    byte[] userByte = HexUtils.intToBytes(int.Parse(item));
                    Array.Copy(userByte, 0, commond, 6 + aid.Length + circleLen, 4);
                    k++;
                }
                
            }

            byte[] dataAll = HeadUtil(commond, 1, transport, sequence, way);


            return dataAll;
        }
        //4002
        public static byte[] DataCommit(string taskId, string sequence, string transport,string way,string json,string operatorUser,string auditorUser)
        {
            //json = File.ReadAllText("提交空包袋登记.txt");
            LogHelper.Debug("json" + json);
            if (taskId == ""|| taskId==null)
            {
                taskId = ltid.ReadMessage();
            }
            LogHelper.Debug("原始taskId===" + taskId);
            string taskIdBin = HexUtils.HexStringToBinString(taskId).Replace(" ", "");
            
            LogHelper.Debug("二进制taskId===" + taskIdBin);
            if (taskIdBin.Substring(0, 1).Equals("1"))
            {
                taskIdBin = "0" + taskIdBin.Substring(1, 31);
                taskId = HexUtils.binStringToHexString(taskIdBin);
                taskId = taskId.PadLeft(8, '0');
            }
            LogHelper.Debug("提交4002任务id" + taskId);
     
            //id = "0"+id.Substring(1, 7);
            long timer = TimerHelper.GetTimeStamp();
            byte[] fragmentByte = new byte[4];
           
            byte[] fragmentRandom = HexUtils.intToBytes(RandomHelper.GetRandomInt());
            Array.Copy(fragmentRandom, 0, fragmentByte, 0, 4);
          
            byte[] idByte = HexUtils.strToHexByte(taskId);
            byte[] jsonByte = Encoding.UTF8.GetBytes(json);
            byte[] datetimeByte = HexUtils.ToBytes(timer);
            byte[] jsonByteLen = HexUtils.intToBytes(jsonByte.Length);
            byte[] operatorUserByte = HexUtils.intToBytes(int.Parse(operatorUser));
            byte[] auditorUserByte = HexUtils.intToBytes(int.Parse(auditorUser));
            
            byte[] data = new byte[28 + jsonByte.Length];
           
            Array.Copy(idByte, 0, data, 0, 4);
            Array.Copy(fragmentByte, 0, data, 4, 4);
            Array.Copy(datetimeByte, 0, data, 8, 8);
            Array.Copy(jsonByteLen, 0, data, 16, 4);
            Array.Copy(jsonByte, 0, data, 20, jsonByte.Length);
            Array.Copy(operatorUserByte, 0, data, 20+ jsonByte.Length, 4);
            Array.Copy(auditorUserByte, 0, data, 24+ jsonByte.Length, 4);
            byte[] transportByte = HexUtils.strToHexByte(transport);
            byte[] dataAll = HeadUtil(data, 1, transport, sequence,way);
           
            string dataExchange = taskId + ":" + HexUtils.byteToHexStr(datetimeByte) + ":" + HexUtils.byteToHexStr(jsonByteLen) + HexUtils.byteToHexStr(jsonByte) + ":" + operatorUser + ":" + auditorUser;
            //ltdata.WriteMessage(dataExchange);
            dataMaker = new TXTHelper(taskId + "data");
            dataMaker.WriteMessage(dataExchange);
            return dataAll;
        }
        //用于只需返回error
        public static byte[] DownCommond(string error,string transport,string sequence,string way)
        {
            byte[] errorByte = null;
            byte[] errorLen = null;
            int errorByteLen = 0;
            if (error == "" || error == null)
            {
                errorLen = HexUtils.intToBytes(errorByteLen);
            }
            else
            {
                errorByte = Encoding.UTF8.GetBytes(error);
                errorByteLen = errorByte.Length;
                errorLen = HexUtils.intToBytes(errorByteLen);
            }
            byte[] data = new byte[4 + errorByteLen];
            if (errorByteLen > 0)
            {
                Array.Copy(errorByte, 0, data, 4, errorByteLen);

            }

            Array.Copy(errorLen, 0, data, 0, 4);
            
            
            byte[] dataAll = HeadUtil(data, 1, transport, sequence,way);
           
            return dataAll;
        }
        /**
         * payLoadsLen 数据区长度
         * synchronous 同步异步，0同步，1异步
         * transport 指令编号
         * way 指定数据是否封包
         * */
        public static byte[] HeadUtil(byte[] data, int synchronous, string transport,string sequence ,string way)
        {
            byte[] dataAll = null;

            int payloadsEncryLen = data.Length;
            string macEncry = "";
            if (way.Equals("11"))
            {
                //必须封包
                string skey = ltskey.ReadMessage();
                string dataEncry = DESHelper.Encrypt3Des(HexUtils.byteToHexStr(data), skey);
                //LogHelper.Debug("封包数据为" + dataEncry);
                byte[] dataDecryByte = DESHelper.Decrypt3Des(dataEncry, skey);
                //LogHelper.Debug("解包数据为" + HexUtils.byteToHexStr(dataDecryByte));

                string mkey = ltmkey.ReadMessage();
                macEncry = DESHelper.Encrypt3Des(dataEncry, mkey);
                //LogHelper.Debug("封包数据MAC为" + macEncry);

                macEncry = macEncry.Substring(macEncry.Length - 16, 8);
                //string macDEcry = DESHelper.Decrypt3Des(dataEncry, mkey).Substring(0, 8);
                //LogHelper.Debug("解包数据MAC" + macEncry);
                data = HexUtils.strToHexByte(dataEncry);
                payloadsEncryLen = data.Length + 4;

            }
            //Console.WriteLine("payloadsEncryLen" + payloadsEncryLen);
            //确定数据长度
            if (data.Length != 0)
            {
                dataAll = new byte[14 + payloadsEncryLen];
            }
            else
            {
                dataAll = new byte[15];
                dataAll[14] = 0x00;
            }
            int sendType = 0;
            if (transport.Equals("4003") || transport.Equals("4002") || transport.Equals("0000"))
            {
                sendType = 1;
            }


            string length = "";
            if (payloadsEncryLen == 0)
            {
                //length = sendType + way.Substring(0, 1) + way + HexUtils.AddLenZero(Convert.ToString(data.Length, 2));
            }
            else
            {

                length = sendType + way.Substring(0, 1) + way + HexUtils.AddLenZero(Convert.ToString(payloadsEncryLen, 2));

            }
            //Console.WriteLine("dataAll" + dataAll.Length);
            //Console.WriteLine("length" + length);
            string lengthTo16 = string.Format("{0:x}", Convert.ToInt32(length, 2));
            //Console.WriteLine("lengthTo16==" + lengthTo16);
            byte[] lenthByte = HexUtils.strToHexByte(lengthTo16.PadLeft(8, '0'));
            Array.Copy(lenthByte, 0, dataAll, 0, 4);
            //同步0，异步1

            if (sequence.Length > 1)
            {
                byte[] sequenceByte = HexUtils.strToHexByte(sequence);

                Array.Copy(sequenceByte, 0, dataAll, 4, 8);
            }

            byte[] transportByte = HexUtils.strToHexByte(transport);
            Array.Copy(transportByte, 0, dataAll, 12, 2);

            Array.Copy(data, 0, dataAll, 14, data.Length);
            //添加数字签名mac
            if (macEncry.Length > 1)
            {

                Array.Copy(HexUtils.strToHexByte(macEncry), 0, dataAll, 14 + data.Length, 4);
            }
            //LogHelper.Debug("发送拼接数据总长度" + dataAll.Length);
            LogicHead lh = HeadHelper.analysisData(dataAll);

            LogHelper.Debug("回复" + lh.toString());
            return dataAll;

        }


    }
}
